import Immutable from 'immutable';
import { routerRedux } from 'dva/router';
import { queryCouponQRStatus, genPayCode, genBarcode, genQrcode, queryOrderByCode } from '../services/code';
import { hasInsuranceInfo } from '../services/insurance';
import toast from '../utils/toast';
import { delay } from '../utils/func';
import { get, save } from '../utils/storage';

export default {
  namespace: 'code',
  state: Immutable.fromJS({
    active: false,
    code: {
      payCode: null,
      barCode: null,
      qrCode: null,
    },
  }),

  effects: {
    *preFetchCouponQRStatus({ payload }, { call, put }) {
      const { id, escort } = payload;
      const showAddInfo = get('showAddInfo');
      const toAddInfo = get('toAddInfo');
      if (showAddInfo !== true && escort === 'escort') {
        const ret = yield call(hasInsuranceInfo, payload);
        save('showAddInfo', ret.data);
        if (ret.data === true && toAddInfo !== 1) {
          save('toAddInfo', 1);
          yield put(routerRedux.push('addInsuranceInfo'));
          return;
        }
      }
      const res = yield call(queryCouponQRStatus, {
        couponDetailId: id,
      });
      if (res.success && res.data.writeOffStatus === 1) {
        toast('该券已被使用');
        yield put({
          type: 'coupon/couponUsed',
          payload,
        });
      } else if (res.success && res.data.outCouponNo) {
        yield put(routerRedux.push(`/escort/couponCode?couponCode=${res.data.outCouponNo}&id=${res.data.couponDetailId}`));
      } else {
        console.error('请求状态出错');
        // toast('');
        // yield put(routerRedux.push(`/escort/couponCode?couponCode=${code}&id=${id}`));
      }
    },
    *fetchCouponQRStatus({ payload }, { call, put, select }) {
      const active = yield select(state => state.code.get('active'));
      if (!active) {
        return;
      }
      const res = yield call(queryCouponQRStatus, payload);
      if (res.success && res.data.writeOffStatus === 1) {
        yield put(routerRedux.push('result?type=code'));
      } else {
        yield call(delay, 2000);
        yield put({
          type: 'fetchCouponQRStatus',
          payload,
        });
      }
    },
    *refreshPayCodeAfter({ payload }, { call, put }) {
      const { expire, ...rest } = payload;
      yield call(delay, expire * 1000);
      yield put({
        type: 'fetchPayCode',
        payload: rest,
      });
    },
    *fetchPayCode({ payload }, { call, put }) {
      const res = yield call(genPayCode, payload);
      if (res.success) {
        const payCode = res.data.authCode;
        const barCode = yield call(genBarcode, payCode);
        const qrCode = yield call(genQrcode, payCode);
        yield put({
          type: 'updatePayCode',
          payload: {
            payCode,
            barCode,
            qrCode,
          },
        });
      }
    },
    *queryOrder({ payload }, { call, put, select }) {
      yield call(delay, 2000);
      const active = yield select(state => state.code.get('active'));
      if (!active) {
        return;
      }
      const res = yield call(queryOrderByCode, payload);
      if (res.success) {
        if (res.data.payCodeStatus === 1) { // 跳转收银台
          yield put(routerRedux.push({
            pathname: '/pay/qijiRefuel',
            state: { order: res.data },
          }));
        } else if (res.data.payCodeStatus === 3) { // 刷新二维码
          yield put.resolve({
            type: 'fetchPayCode',
          });
        }
      }
      yield put({
        type: 'queryOrder',
      });
    },
    *initCodeRefuel(_, { put }) {
      yield put.resolve({
        type: 'fetchPayCode',
      });
      yield put({
        type: 'queryOrder',
      });
    },
  },

  reducers: {
    updatePayCode(state, { payload }) {
      return state.mergeIn(['code'], payload);
    },
    updateActive(state, { payload }) {
      return state.set('active', payload);
    },
  },
};
